(function() {
	angular
    	.module('mxu',[])
    	.controller('loginCtrl', loginCtrl);
    	loginCtrl.$inject = ['$scope','$http','$timeout'];
      	function loginCtrl($scope,$http,$timeout) {
      		var vm = $scope.vm = {};
      		angular.extend( vm,{
      			// loginUrl : window.CONFIG.apiUrl + '/api/login',
				// resetUrl : window.CONFIG.apiUrl + '/api/auth/user/reset_password/{id}',
      		   //  checkUser : window.CONFIG.checkUser,
      		    mainPage : window.CONFIG.baseUrl + '/main/app/home/index',
      			init : function(){
					vm.login_loading = false;
					// vm.isNeedReset=false;
      				// var token = vm.cookie('mxu_token');
      				// if( token ){
      				// 	location.href = vm.mainPage;
      				// }
      			},
      			
      			login : function(){
					location.href = vm.mainPage;
					return false;

      				vm.errorMessage = '';
      				vm.userInfo.remember = vm.remember ? 1 :0;
      				var ajaxParam = {
			   			url : vm.loginUrl,
			   			method : 'POST',
			   			headers : {},
			   			data : vm.userInfo,
			   			withCredentials : true
			   		};
			   		var time = vm.userInfo.remember ? 7 : 0.4;
			   		if( !vm.userInfo || !vm.userInfo.username || !vm.userInfo.password){
			   			return false;
			   		}
			   		vm.login_loading = true;
			   		$http(ajaxParam)
			   		.success(function( data ){
			   			vm.login_loading = false;
						vm.storage.clear();
			   			if( data && (data.error_code || data.error_message)){
			   				vm.errorMessage = data.error_message || '访问错误';
							vm.userInfo.password='';
      						return false;
      					}
      					if( data.data && data.data.id){
							if(data.data.reset_pwd=='1'){
								vm.isNeedReset=true;
								vm.userId=data.data.id;
							}else{
								var param= {
									expires: time,
									path   : window.CONFIG.cookiePath,
									domain : window.CONFIG.cookieDomain
								};
								vm.cookie('mxu_token',data.data._token,param);
								$timeout(function(){
									location.href = vm.mainPage + '?remember='+vm.userInfo.remember;
								},50)
							}
      					}
			   		})
			   		.error(function(){
			   			vm.login_loading = false;
			   		})
      			},

				save:function(){
					var param={
						old_password:vm.userInfo.originPassword,
						password:vm.userInfo.newPassword,
						confirm_password:vm.userInfo.conformPassword
					};
					var ajaxParam = {
						url : vm.resetUrl.replace('{id}',vm.userId),
						method : 'PUT',
						headers : {},
						data : param,
						withCredentials : true
					};

					$http(ajaxParam)
						.success(function( data ){
							vm.login_loading = false;
							if( data && (data.error_code || data.error_message)){
								vm.errorSetMessage = data.error_message || '访问错误';
								vm.userInfo='';
								return false;
							}
							if( data.data){
								vm.successTip=true;
								$timeout(function(){
									vm.isNeedReset=false;
								},1500);
							}
						})
						.error(function(){
							vm.login_loading = false;
						})
				},

      			cookie : function(name, value, options) {
				    if (typeof value != 'undefined') {
				        options = options || {};
				        if (value === null) {
				            value = '';
				            options.expires = -1;
				        }
				        var expires = '';
				        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				            var date;
				            if (typeof options.expires == 'number') {
				                date = new Date();
				                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				            } else {
				                date = options.expires;
				            }
				            expires = '; expires=' + date.toUTCString();
				        }
				        var path = options.path ? '; path=' + options.path : '';
				        var domain = options.domain ? '; domain=' + options.domain : '';
				        var secure = options.secure ? '; secure' : '';
				        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
				    } else {
				        var cookieValue = null;
				        if (document.cookie && document.cookie != '') {
				            var cookies = document.cookie.split(';');
				            for (var i = 0; i < cookies.length; i++) {
				                var cookie = $.trim(cookies[i]);
				                if (cookie.substring(0, name.length + 1) == (name + '=')) {
				                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
				                    break;
				                }
				            }
				        }
				        return cookieValue;
				    }
				},
      			
      			storage : {
					method : 'localStorage',
					get : function( key, method ){
						method = method || this.method;
						var data = JSON.parse( window[method].getItem( key ) );
						return data && data.value ? data.timestamp === null ? JSON.parse( data.value ) : ( new Date ).getTime() < data.timestamp && JSON.parse( data.value ) || !1 : !1;
					},
					remove : function( key, method ){
						method = method || this.method;
						window[method].removeItem( key );
					},
					clear : function( method ){
						method = method || this.method;
						window[method].clear();
					}
			  	}
      		});
      		vm.init();
      	}
})();